const { File } = require("ada-util");
const Path = require("path");
const BaseInstaller = require('./../util/installer');

class Installer extends BaseInstaller {
	constructor(config) {
		super({
			path: config.projectPath,
			agent: config.agent,
			hooker: config.hooker
		});
		this._config = config;
	}

	get config() {
		return this._config;
	}

	getFileTypesOfProject() {
		return new File(this.config.sourcePath).getAllSubFilePaths().then(paths => paths.map(path => Path.extname(path)).filter(a => !!a).map(a => a.substring(1)));
	}

	readyTypeModules(type) {
		let map = this.config.dependence;
		if (map[type]) {
			let target = Reflect.ownKeys(map[type]).map(name => {
				return { name, version: map[type][name] };
			});
			return this.checkUnInstalledModules(target).then(result => {
				return this.installModules(result);
			});
		} else {
			return Promise.resolve();
		}
	}

	readyProjectModules() {
		let target = {};
		Reflect.ownKeys(this.config.dependence).forEach(type => {
			let t = this.config.dependence[type];
			Object.assign(target, t || {});
		});
		target = Reflect.ownKeys(target).map(name => {
			return { name, version: target[name] };
		});
		return this.checkUnInstalledModules(target).then(result => {
			return this.installModules(result);
		});
	}
}

module.exports = Installer;